package org.sagitta.httprpc.hessian.adaptor;

import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sagitta.httprpc.RequestUnmarshaller;
import org.sagitta.httprpc.exception.RPCException;

import com.caucho.hessian.io.AbstractHessianInput;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.SerializerFactory;

public class HessianRequestUnmashaller implements RequestUnmarshaller {

	private static final Log log = LogFactory.getLog(HessianRequestUnmashaller.class);
	private SerializerFactory serializerFactory;

	@SuppressWarnings("unchecked")
	@Override
	public <T> T unmashal(Class<T> requestClass, InputStream data) throws RPCException {
		AbstractHessianInput in = new Hessian2Input(data);
		in.setSerializerFactory(serializerFactory);
		try {
			in.startReply();
			Object obj = in.readObject();
			in.completeReply();
			in.close();
			if (obj.getClass().equals(requestClass)) {
				return (T) obj;
			} else {
				if (log.isDebugEnabled()) {
					log.debug("It is not a validate class type, it is an instance of " + obj.getClass());
				}
				throw new RPCException(RPCException.REQUESTMASHLLERROR);
			}
		} catch (Throwable e) {
			e.printStackTrace();
			throw new RPCException(RPCException.REQUESTMASHLLERROR);
		}
	}

	public SerializerFactory getSerializerFactory() {
		return serializerFactory;
	}

	public void setSerializerFactory(SerializerFactory serializerFactory) {
		this.serializerFactory = serializerFactory;
	}

}
